const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 创建上传目录
const createUploadDir = () => {
  const uploadPath = path.join(__dirname, '../../img');
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
  }
  return uploadPath;
};

// 生成唯一文件名
const generateFileName = (prefix, originalname) => {
  const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
  return prefix + '_' + uniqueSuffix + path.extname(originalname);
};

// 文件过滤器
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件'), false);
  }
};

// 创建multer配置
const createMulterConfig = (filePrefix) => {
  const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      const uploadPath = createUploadDir();
      cb(null, uploadPath);
    },
    filename: function (req, file, cb) {
      const filename = generateFileName(filePrefix, file.originalname);
      cb(null, filename);
    }
  });

  return multer({ 
    storage: storage,
    fileFilter: fileFilter,
    limits: {
      fileSize: 5 * 1024 * 1024 // 5MB
    }
  });
};

// 导出不同用途的上传中间件
module.exports = {
  // 作家头像上传
  writerUpload: createMulterConfig('writer'),
  
  // 作品封面上传
  workUpload: createMulterConfig('work'),
  
  // 通用图片上传
  imageUpload: createMulterConfig('img'),
  
  // 删除文件的工具函数
  deleteFile: (filePath) => {
    if (filePath) {
      const fullPath = path.join(__dirname, '../..', filePath);
      if (fs.existsSync(fullPath)) {
        fs.unlinkSync(fullPath);
      }
    }
  }
};